#!/bin/bash

source ./build_utils.sh

install_prereq()
{
    arr=(gcc mkisofs wget make)
    for n in `seq 0 $(( ${#arr[@]} - 1 ))`; do
        echo -n "Checking for ${arr[$n]} ... "
        i=$(which ${arr[$n]} >/dev/null 2>&1)
        if [[ $? -eq 1 ]]; then
            echo "Failed."
            echo "Installing ${arr[$n]}"
            yum install -y ${arr[$n]}
        else
            echo "Success."
        fi 
    done

    becho "Install prequisite packages for core packages"
    yum install -y bzip2-devel
    yum install -y libxml2
    yum install -y libxml2-devel
    yum install -y libperl
    yum install -y perl
    yum install -y perl-devel
    yum install -y openssl
    yum install -y openssl-devel
    yum install -y pcre-devel
    yum install -y pango
    yum install -y pango-devel
    yum install -y squashfs-tools
    yum install -y livecd-tools
    yum install -y createrepo
    yum install -y yum-utils
    yum install -y dosfstools

    becho "Download rpms needed for iso build"
    yumdownloader --destdir=app_repo syslinux
    yumdownloader --destdir=app_repo perl-Regexp-Common
    yumdownloader --destdir=app_repo libxml2*
    yumdownloader --destdir=app_repo mtools

    ARCH=$(uname -i)
    
    if [[ `grep Fedora /etc/redhat-release` ]]; then
        DIST=fc10
    else
        DIST=centos55
        rpm -ivh http://mirror.ribalba.de/centos-livecd/x86_64/live/RPMS/pykickstart-1.0-2.noarch.rpm
        rpm -ivh http://mirror.ribalba.de/centos-livecd/x86_64/live/RPMS/livecd-tools-014-8.x86_64.rpm
    fi

    #sed -e "s!ARCH=.*!ARCH=$ARCH!" -e "s!INSTALL_PREREQ=[0-9]!INSTALL_PREREQ=0!" $ROOT/conf/build.config > build.config.tmp
    sed -e "s!ARCH=.*!ARCH=$ARCH!" -e "s!DIST=.*!DIST=$DIST!" $ROOT/conf/build.config > build.config.tmp
    mv build.config.tmp $ROOT/conf/build.config

    ln -s $TMPDIR/staging $STAGING
    ln -s $TMPDIR/tarballs $SRCDIR

    echo "      
    Swap the order of the two functions below in /usr/lib/python2.5/site-packages/imgcreate/creator.py
        self.__run_post_scripts()
        self._create_bootconfig()
    Remove prelink checking in RPM by commenting out the following line in /etc/rpm/macros.prelink
    #%__prelink_undo_cmd     /usr/sbin/prelink prelink -y library
    "
    echo -n "Hit Enter to continue: "
    read a
}

#Build base pkgs for base appliance
build_base_pkg()
{
    cd $ROOT
    sed -e "s!STAGING!$STAGING!g" $BASEPKGLIST > $BASEPKGLIST.tmp
    becho "Build Base pkgs ..."
    while read i
    do
        cd $SRCDIR
        if [[ $i =~ "^#" ]]; then
            continue
        fi
        build_pkg "$i"
        build_rpm "$i"
    done < $BASEPKGLIST.tmp
    rm -f $BASEPKGLIST.tmp
}

#Build core pkgs for busybox install
build_core_pkg()
{
    cd $ROOT
    sed -e "s!STAGING!$STAGING!g" -e "s!ROOT!$ROOT!g" $COREPKGLIST > $COREPKGLIST.tmp

    becho "Build core packages ..."
    while read i
    do
        cd $SRCDIR
        if [[ $i =~ "^#" ]]; then
            continue
        fi
        build_pkg "$i"
    done < $COREPKGLIST.tmp
}

#Build kernel
build_kernel()
{
    cd $ROOT
    becho "Build kernel ..."
    cd $SRCDIR
    file=$(find $SRCDIR -name \*linux-2.6\*.bz2 -type f)
    dir=$(untar $file)
    cd $dir
    cp $ROOT/conf/kernel.config .config
    make clean && make && make modules && make tarbz2-pkg
    cp linux-2.6*.tar.bz2 $ROOT
}

#Build the specified app
build_app()
{
    cd $ROOT
    if [[ ! -d $APPDIR/$1 ]]; then
        echo "app directory ($APPDIR/$1) for $1 does not exists"
        return 0
    fi
    
    build_pkg_list $APPDIR/$1/pkglist
    build_rpm_list $APPDIR/$1/pkglist
}

#make the app template
make_app()
{
    app=$1
    mkdir -p $APPDIR/${app}
    mkdir -p $APPDIR/${app}/{conf,scripts}

    echo "#name;version;download url;buildstep 1;...;buildstepN" > $APPDIR/${app}/pkglist
    cp $APPDIR/base/conf/iptables $APPDIR/${app}/conf/

    #create app kickstart template
    echo "
#${app} appliance
lang en_US.UTF-8
keyboard us
timezone US/Pacific
auth --useshadow --enablemd5
selinux --disabled
firewall --enable
part / --size 1024
rootpw --iscrypted \$1\$JNPhe66E\$irdx52QGvt.1ELbl6B2ht/

repo --name=dev --baseurl=file:///mnt/
repo --name=app --baseurl=file://APP_REPO

%packages --nobase --excludedocs
${app}


%post
%end

%post --nochroot
source ./build_utils.sh

APP=${app}

cp -a \$APPDIR/\$APP/conf/iptables \$INSTALL_ROOT/etc/sysconfig/iptables
cp -a \$APPDIR/\$APP/conf/splash.jpg \$INSTALL_ROOT/usr/lib/anaconda-runtime/syslinux-vesa-splash.jpg

#setup custom files
#config the lab.conf file
sed -i -e "s!APP=.*!APP=\$APP!" \$INSTALL_ROOT/etc/lab/lab.conf
sed -i -e "s!HOSTNAME=.*!HOSTNAME=lab-\$APP!" \$INSTALL_ROOT/etc/sysconfig/network
echo "\$VERSION" > \$INSTALL_ROOT/etc/lab/lab-version

%end
    " > $APPDIR/${app}/lab-${app}.ks
}


#install rootfs using busybox
install_bb_core()
{
    becho "Cleanup $ROOTFS"
    rm -rf $ROOTFS*
    mkdir $ROOTFS
    mkdir -p $ROOTFS/lib64
    cd $ROOT
    becho "Create busybox based base rootfs ..."
    becho "Create rootfs directory structure" 

    mkdir -p $ROOTFS/var/lib/rpm
    rpm --initdb --root $ROOTFS

    becho "Copy etc files to $ROOTFS"
    cp -a $ROOT/scripts/etc $ROOTFS

    install_rpm $STAGING/RPMS/$ARCH/busybox-*.rpm --nodeps --noscripts
    install_rpm $STAGING/RPMS/$ARCH/bash-*.rpm --nodeps
    install_rpm $STAGING/RPMS/$ARCH/udev-*.rpm --nodeps
    install_rpm $STAGING/RPMS/$ARCH/e2fsprogs-*.rpm --nodeps --force
    install_rpm $STAGING/RPMS/$ARCH/iproute2-*.rpm --nodeps

    becho "Copy necessary files from host system to $ROOTFS"
    sh copy_libs.sh
    sh copy_files.sh

    APP=core
}

install_rpm_core()
{
    ROOTFS=$COREFS
    becho "Cleanup $ROOTFS"
    rm -rf $ROOTFS*
    mkdir $ROOTFS
    cd $ROOT
    becho "Create yum-based base rootfs ..."
    mkdir -p $ROOTFS/etc
    cp $ROOT/conf/yum.conf $ROOTFS/etc

    mount_cd

    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS groupinstall -y core
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y kernel
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y openssh-server
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y openssh-clients
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y iptables
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y vixie-cron
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y bc
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS remove -y sendmail
    yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS remove -y audit
    remove_rpm redhat-logos --nodeps
    remove_rpm fedora-release-notes --nodeps

    cp -a $ROOT/scripts/init.rpm $ROOTFS/init
    cp -a $ROOT/scripts/etc/fstab $ROOTFS/etc/
    cp -a $ROOT/scripts/etc/rc.d/rc.local $ROOTFS/etc/rc.d/
    cp -a $ROOT/scripts/etc/issue $ROOTFS/etc/
    cp -a $ROOT/scripts/etc/lab $ROOTFS/etc/
    cp -a $ROOT/scripts/etc/sysconfig/network $ROOTFS/etc/sysconfig
    cp -a $ROOT/scripts/etc/sysconfig/network-scripts/ifcfg-eth0 $ROOTFS/etc/sysconfig/network-scripts
    cp -a $ROOT/scripts/etc/sysconfig/network-scripts/ifmode $ROOTFS/etc/sysconfig/network-scripts
    cp -a $ROOT/scripts/etc/modprobe.d $ROOTFS/etc/
    cp -a $ROOT/scripts/etc/sysctl.conf $ROOTFS/etc/

    chroot $ROOTFS /bin/bash -c "pwconv"
    chroot $ROOTFS /bin/bash -c "echo 'labb' | passwd root --stdin"
    chroot $ROOTFS /bin/bash -c "chkconfig --level 3 network on"
    chroot $ROOTFS /bin/bash -c "chkconfig --level 3 exim off"

    APP=core
}

copy_core()
{
    becho "Cleanup $ROOTFS"
    rm -rf $ROOTFS*
    mkdir $ROOTFS
    cd $ROOT
    becho "Copying $COREFS $ROOTFS"
    cp -a $COREFS/* $ROOTFS/
}

setup_rootfs()
{
    becho "Do additional setup work for $ROOTFS"
    ldconfig -r $ROOTFS

    #config the lab.conf file
    sed -i -e "s!APP=.*!APP=$APP!" $ROOTFS/etc/lab/lab.conf
    sed -i -e "s!HOSTNAME=.*!HOSTNAME=lab-$APP!" $ROOTFS/etc/sysconfig/network
    echo "$VERSION" > $ROOTFS/etc/lab/lab-version
}

#Install kernel
install_kernel()
{
    becho "Copy kernel files to $ROOTFS"
    #install_rpm $ROOT/kernel-2.6.32.6LAB_V0.1-1.i386.rpm
    install_rpm kernel --nodeps
}


build_iso()
{
    becho "Create initramfs"
    cd $ROOTFS && find . | cpio -H newc -o > $ROOTFS.cpio && cd $ROOT && gzip $ROOTFS.cpio -c > $ROOTFS.igz

    rm -rf $STAGING/iso
    cp -a iso $STAGING/iso

    becho "Create iso"
    find $STAGING/iso -type d -name .svn | xargs rm -rf
    rm -f $ROOT/$ISONAME.iso
    cp -a $ROOTFS.igz $STAGING/iso/isolinux/rootfs.igz
    cp -a $ROOTFS/boot/vmlinuz* $STAGING/iso/isolinux/vmlinuz

    ISONAME=${ISONAME}-${VERSION}.${ARCH}.${DIST}
    cd $STAGING/iso 
    mkisofs -v -pad -o $ROOT/$ISONAME.iso -V "Linux Appliance Box" -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -J -r -T .

    cd $ROOT
    rm -f $ROOTFS.cpio
    rm -f $ROOTFS.igz
}

build_live_iso()
{
    size=$(du -kxs $ROOTFS | awk '{printf("%d", $1)}')
    size=$(echo "$size + 90000" | bc)
    echo "Creating $ROOTFS.img ..."
    dd if=/dev/zero of=$ROOTFS.img bs=1k count=$size
    mkfs.ext3 -F $ROOTFS.img

    echo "Copying $ROOTFS to mntpnt ..."
    mkdir -p mntpnt
    mount -o loop $ROOTFS.img mntpnt
    cp -a $ROOTFS/* mntpnt/
    umount mntpnt

    mkdir -p sqfs/LiveOS
    mv $ROOTFS.img sqfs/LiveOS/ext3fs.img

    rm -rf $STAGING/live_iso
    cp -a live_iso $STAGING/live_iso
    mkdir -p $STAGING/live_iso/LiveOS
    mksquashfs sqfs $STAGING/live_iso/LiveOS/squashfs.img -noappend

    ISONAME=${ISONAME}-${VERSION}.${ARCH}.${DIST}
    cd $STAGING/live_iso 
    mkisofs -R -l -L -D -b isolinux/isolinux.bin -c isolinux/boot.catalog -o $ROOT/$ISONAME.live.iso -no-emul-boot -boot-load-size 4 -boot-info-table -V "LAB-x86_64-Live" .

    cd $ROOT
    rm -rf sqfs $ROOTFS.img
}

help()
{
    echo "Usage: sh $0 <command>"
    echo "command:"
    echo "build_core: Builds the core appliance using rpms"
    echo "build_rpm_base: Builds the base appliance using rpms"
    echo "buildapp <appname>: Builds a specific appliance off the base appliance"
    echo "makeapp <appname>: Make a template dir and basic file for a new appliance"
    echo "iso <appname>: Builds an iso of the app specific with appname"
    echo "setup: Run-once, Run-first command to setup the environment"
    echo "run <function>: runs the next argument as a function if it exists in this script."
    echo "help: This message"
}

################### Start ####################

echo

case "$1" in
    build_core)
        ISONAME="${ISONAME}-core-${VERSION}-${DIST}-${ARCH}"
        ROOTFS=$COREFS
        becho "Running in $ROOT. Will build rootfs in $ROOTFS" 
        /usr/bin/livecd-creator -c lab-core.ks -f ${ISONAME}
        RETVAL=$?
        ;;
    build_bb_core)
        ISONAME="${ISONAME}-core-bb"
        becho "Running in $ROOT. Will build rootfs in $ROOTFS" 
        install_bb_core
        install_kernel
        setup_rootfs
        build_iso
        RETVAL=$?
        ;;
    build_bb_base)
        ISONAME="${ISONAME}-base-bb"
        becho "Running in $ROOT. Will build rootfs in $ROOTFS" 
        copy_core
        install_kernel
        setup_rootfs
        build_iso
        RETVAL=$?
        ;;
    setup)
        mkdir -p $LOGDIR
        mkdir -p $APP_REPO
        mount_cd
        install_prereq
        RETVAL=$?
        ;;
    iso)
        if [[ $2 != "" ]]; then
            APP=$2
            ISONAME="${ISONAME}-${APP}-${VERSION}-${DIST}-${ARCH}"
            /usr/bin/createrepo $APP_REPO
            sed -e "s!APP_REPO!$APP_REPO!" -e "s!APP_NAME!$APP!" $APPDIR/$APP/lab-$APP.ks > lab-$APP.ks

            if [[ $APP == "base" ]]; then
                /usr/bin/livecd-creator -t /sdb1/tmp -c lab-$APP.ks -f ${ISONAME}
            else
                /usr/bin/livecd-creator -t /sdb1/tmp -c lab-$APP.ks -b lab-base-${VERSION}-${DIST}-${ARCH}.iso -f lab-$APP
                if [[ $? -eq 0 ]]; then
                    echo "Moving iso to $ISONAME"
                    mv lab-$APP.iso $ISONAME.iso
                fi

            fi
        else
            echo "Specify the fs dir to build the iso from"
        fi
        RETVAL=$?
        ;;
    buildapp)
        if [[ $2 != "" ]]; then
            APP=$2
            build_app $APP
        else
            echo "Specify an app name"
        fi
        RETVAL=$?
        ;;
    makeapp)
        if [[ $2 != "" ]]; then
            APP=$2
            make_app $APP
        else
            echo "Specify an app name"
        fi
        RETVAL=$?
        ;;
    run)
        shift
        $3 $@
        RETVAL=$?
        ;;
    help)
        help
        RETVAL=$?
        ;;
    *)
        help
        RETVAL=$?
esac

exit $RETVAL
